<template>
  <div class="home_container">
    <div class="process_box">
      <el-progress :percentage="50" color="#0fcb8c"> </el-progress>
      <div>recive file</div>
    </div>
    <div class="card_list">
      <div v-for="(result, index) in resultList" :key="index + result.result" class="card">
        <div class="card_title">
          <div>Page {{ index + 1 }}</div>
          <div>
            {{ result.tokenNum }} tokens processed
            <span @click="copyContent(result)" class="copy_btn">
              <img src="@/assets/svg/copy.svg" alt="" />Copy
            </span>
          </div>
        </div>
        <div class="card_content">
          <div v-loading="leftLoading" element-loading-text="Processing.." class="card_content_img">
            <img :src="result.img" alt="" />
          </div>
          <div
            v-loading="rightLoading"
            element-loading-text="Processing.."
            class="card_content_result"
          >
            <div>
              <v-md-editor :model-value="testText" mode="preview" ref="preview"></v-md-editor>
            </div>
            <div class="result_metadata">
              <h4>Page Metadata</h4>
              <div><strong>Primary language：</strong>zh</div>
              <div><strong>Is rotation valid：</strong>zh</div>
              <div><strong>Rotation correction：</strong>zh</div>
              <div><strong>Is a table：</strong>zh</div>
              <div><strong>Is a diagram：</strong>zh</div>
              <div @click="openPromptDialog(result)" class="view_prompt_btn">View Prompt</div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="resultList.length > 0" class="limit_box">
        <div class="limit_box_title">Preview is limited to {{ limitPages }} pages.</div>
        <div class="limit_box_tips">
          Check out our GitHub and run on your own hardware to convert as many documents for free as
          you like.
        </div>
      </div>
    </div>
    <div class="upload_box">
      <div class="upload_text">Analyze any PDF, JPG, or PNG</div>
      <div>
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          accept=".pdf,.jpg,.png"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleChange"
        >
          <div class="upload_box_btn">
            <div>
              <img src="@/assets/svg/upload.svg" alt="" />
            </div>
            <span v-if="!uploadFile"
              >Drag and drop a file here or click to browse the file system</span
            >
            <span v-else>{{ uploadFile.name }}</span>
          </div>
        </el-upload>
      </div>
    </div>
    <div v-if="uploadFile" class="upload_btn">
      <el-button type="success" @click="processDocument" plain>Process Document</el-button>
    </div>
    <div class="sample_list">
      <h2>Or try a sample document</h2>
      <div class="sample_box">
        <div v-for="item in sampleList" :key="item.sampleTitle" class="sample_card">
          <div class="sample_img">
            <img :src="item.sampleImg" alt="" />
          </div>
          <div class="sample_text">{{ item.sampleTitle }}</div>
        </div>
      </div>
    </div>
    <PromptDialog v-model:modelValue="promptDialogVis" :promptText="promptText" />
  </div>
</template>

<script setup lang="ts">
import { ref, type Ref } from 'vue'
import copy from 'copy-to-clipboard'
import PromptDialog from './components/PromptDialog.vue'
import type { UploadFile } from 'element-plus'
import { useProxy } from '@/utils/common'
import { arrayBufferToBase64, sliceAndUploadFile } from '@/utils/file'

// 测试数据
const testText = `
<h2>(二) 按所有权归属分类</h2>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>1. 归属于母公司股东的净利润（净亏损以“-”号填列）</td>
<td>1,200,510</td>
<td>1,000,757</td>
</tr>
<tr>
<td>2. 少数股东损益（净亏损以“-”号填列）</td>
<td>104,408</td>
<td>94,516</td>
</tr>
</tbody></table>
<h3>六、其他综合收益的税后净额</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>归属母公司股东的其他综合收益的税后净额</td>
<td>205,700</td>
<td>16,484</td>
</tr>
<tr>
<td>(一) 不能重分类进损益的其他综合收益</td>
<td>77,961</td>
<td>27,761</td>
</tr>
<tr>
<td>1. 其他权益工具投资公允价值变动</td>
<td>77,961</td>
<td>27,761</td>
</tr>
<tr>
<td>(二) 将重分类进损益的其他综合收益</td>
<td>127,739</td>
<td>-11,277</td>
</tr>
<tr>
<td>1. 权益法下可转损益的其他综合收益</td>
<td>5,098</td>
<td>-2,011</td>
</tr>
<tr>
<td>2. 以公允价值计量且其变动计入其他综合收益的金融资产公允价值变动</td>
<td>-13,072</td>
<td>11,259</td>
</tr>
<tr>
<td>3. 以公允价值计量且其变动计入其他综合收益的金融资产信用损失准备</td>
<td>135,713</td>
<td>-20,525</td>
</tr>
<tr>
<td>归属于少数股东的其他综合收益的税后净额</td>
<td>-</td>
<td>-</td>
</tr>
</tbody></table>
<h3>七、综合收益总额</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>归属于母公司股东的综合收益总额</td>
<td>1,406,210</td>
<td>1,017,241</td>
</tr>
<tr>
<td>归属于少数股东的综合收益总额</td>
<td>104,408</td>
<td>94,516</td>
</tr>
</tbody></table>
<h3>八、每股收益:</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>(一) 基本每股收益 (元/股)</td>
<td>0.44</td>
<td>0.37</td>
</tr>
<tr>
<td>(二) 稀释每股收益 (元/股)</td>
<td>不适用</td>
<td>不适用</td>
</tr>
</tbody></table>

`

interface resultItem {
  tokenNum: number
  img: string
  result: string
  promptText: string
}
const proxy = useProxy()

// 最大页数
const limitPages = 10

const sampleList: { sampleImg: string; sampleTitle: string }[] = [
  {
    sampleImg: 'https://olmocr.allenai.org/olmo2_preview-cq20eeaz.png',
    sampleTitle: 'Academic Papers',
  },
  {
    sampleImg: 'https://olmocr.allenai.org/openstax-calculus-vol1-273-277_preview-vxvt5cw4.png',
    sampleTitle: 'Math Textbooks',
  },
  {
    sampleImg: 'https://olmocr.allenai.org/olmo2_preview-cq20eeaz.png',
    sampleTitle: 'Academic Papers',
  },
  {
    sampleImg: 'https://olmocr.allenai.org/olmo2_preview-cq20eeaz.png',
    sampleTitle: 'Academic Papers',
  },
]
const fileList: Ref<UploadFile[]> = ref([])
const uploadFile: Ref<File | undefined> = ref()
const promptDialogVis: Ref<boolean | undefined> = ref(false)
const leftLoading: Ref<boolean> = ref(false)
const rightLoading: Ref<boolean> = ref(false)
const promptText: Ref<string> = ref('')
const socket: Ref<WebSocket | undefined> = ref()
const resultList: Ref<resultItem[]> = ref([
  {
    tokenNum: 1000,
    img: 'https://olmocr.allenai.org/olmo2_preview-cq20eeaz.png',
    promptText: '',
    result: '',
  },
  {
    tokenNum: 1000,
    img: 'https://olmocr.allenai.org/olmo2_preview-cq20eeaz.png',
    promptText: '',
    result: '',
  },
])
const handleChange = (file: UploadFile) => {
  const maxSize = 50 // 最大文件大小, 单位：MB
  if ((file.size && file.size > maxSize * 1024 * 1024) || !file.size) {
    fileList.value = fileList.value.filter((item) => item.uid !== file.uid)
    return proxy.$message.error('文件大小不能超过' + maxSize + 'MB')
  }
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'] // 允许的文件类型
  if ((file.raw && !allowedTypes.includes(file.raw.type)) || !file.raw) {
    fileList.value = fileList.value.filter((item) => item.uid !== file.uid)
    return proxy.$message.error('请上传JPG、PNG、PDF格式的文件')
  }
  uploadFile.value = file.raw
}
const copyContent = (result: resultItem) => {
  const isCopied = copy(testText)
  proxy.$message.success(isCopied ? '复制成功' : '复制失败')
}
const openPromptDialog = (result: resultItem) => {
  promptText.value = testText
  promptDialogVis.value = true
}
const uploadHandler = (chunk: ArrayBuffer, endFlag: boolean) => {
  const baseFile = arrayBufferToBase64(chunk)
  const data = {
    samples: baseFile,
    endFlag: endFlag,
    sessionParam: {
      aue: 'wav',
      bos: '999999999',
      eos: '180000',
      rate: '16k',
      rse: 'utf8',
      rst: 'plain',
      sid: '30257f1f-16ca-4932-8d4cc-1a2d300d3579000',
    },
  }
  // 将数据转换为JSON字符串
  const jsonData = JSON.stringify(data)
  // 发送数据
  socket.value!.send(jsonData)
}
const processDocument = () => {
  resultList.value = []
  document.documentElement.scrollTop = 0
  // 准备要发送的数据
  const host = '193.108.153.9:31550'
  // 创建WebSocket对象
  socket.value = new WebSocket('ws://' + host + '/createRec')

  const vm = this

  // 连接打开时触发
  socket.value.onopen = function (event) {
    // 1280 是分片的大小
    uploadFile.value && sliceAndUploadFile(uploadFile.value, uploadHandler, 1280)
  }

  // 接收消息时触发
  socket.value.onmessage = function (event) {}

  // 连接关闭时触发
  socket.value.onclose = function (event) {
    socket.value = undefined
    console.log('WebSocket connection closed:', event)
  }

  // 发生错误时触发
  socket.value.onerror = function (error) {
    socket.value = undefined
    console.error('WebSocket error:', error)
  }
}
</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
